package com.lucene.blog.listener;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.lucene.blog.bean.Blog;
import com.lucene.blog.bean.BlogType;
import com.lucene.blog.bean.Blogger;
import com.lucene.blog.bean.Link;
import com.lucene.blog.db.service.BlogService;
import com.lucene.blog.db.service.BlogTypeService;
import com.lucene.blog.db.service.BloggerService;
import com.lucene.blog.db.service.LinkService;

@Component
public class InitBloggerData implements ServletContextListener, ApplicationContextAware {

	private static ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		InitBloggerData.applicationContext = applicationContext;
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("applicationContext: " + applicationContext);
		
		ServletContext application = sce.getServletContext();
		
		BloggerService bloggerService = (BloggerService) applicationContext.getBean("bloggerService");
		// 获取博主信息
		Blogger blogger = null;
		try {
			blogger = bloggerService.getBloggerData();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// 由于密码也获取到，比较敏感，不需要这个，所以清空掉
		blogger.setPassword("");
		// 将博主信息存入到application中
		application.setAttribute("blogger", blogger);
		
		// 获取友情链接信息
		LinkService linkService = (LinkService) applicationContext.getBean("linkService");
		List<Link> linkList = null;
		try {
			linkList = linkService.getLinkData();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		application.setAttribute("linkList", linkList);
		
		// 获取博客类别信息
		BlogTypeService blogTypeService = (BlogTypeService) applicationContext.getBean("blogTypeService");
		List<BlogType> blogTypeList = null;
		try {
			blogTypeList = blogTypeService.getBlogTypeData();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		application.setAttribute("blogTypeList", blogTypeList);
		
		// 获取按照时间分类的博客信息
		BlogService blogService = (BlogService) applicationContext.getBean("blogService");
		List<Blog> blogList = null;
		try {
			blogList = blogService.getBlogData();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		application.setAttribute("blogList", blogList);
	}

}
